package com.mc.metaSearch;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class baiduURLparse {
	final String prefix = "http://enenba.com/tool/baidu_link_url_jiemi/?url=";

	public String getContent(String url) throws IOException {
		StringBuffer sb = new StringBuffer();
		sb.append(prefix).append(url);
		URL l = new URL(sb.toString());
		HttpURLConnection con = (HttpURLConnection) l.openConnection();
		con.setConnectTimeout(10000);
		con.setReadTimeout(18000);
		BufferedReader r = new BufferedReader(new InputStreamReader(
				l.openStream(), "utf-8"));// "GBK"
		StringBuffer buf = new StringBuffer();
		String str = null;
		while ((str = r.readLine()) != null) {
			buf.append(str);
			str = null;
		}
		return buf.toString();
	}

	public String getURL(String content) {
		Pattern p = Pattern.compile("301�ó���ʵ��urlΪ.*<br />");
		String urls="";
		int k = 0;
		Matcher m = p.matcher(content);
		if (m.find()) {
			String[] src = m.group().split("301�ó���ʵ��urlΪ");
			for (String url : src) {
				String url1 = url.replaceAll(" &nbsp;��", " ")
						.replaceAll("<br.*", "").replaceAll("\"", "")
						.replaceAll(">.*", "");
				if (!(url1.isEmpty() || url1.equals(""))) {
					urls=url1;
				}
			}
		}
		return urls;
	}
	static public void main(String[] args) throws IOException {
		baiduURLparse bd = new baiduURLparse();
		String content=bd.getContent("http://www.baidu.com/link?url=_8KMCkM0zeuE1DY1WMW9VuK1WI8h-jhS204Hs5y7DOvT3Bgm5R9d06wahBGs9Gkx");
		System.out.println(bd.getURL(content));
	}
}
